#include <iostream>
#include <io.h>    
#include <direct.h>
#include <string>
#include <ctime>
#include "GainOffset.h"

using namespace std;

void getFiles( string, vector<string>& );//go through a file folder

int main()
{
	clock_t tp1,tp2;
	vector<unsigned short*> images;
	int sizeX = 1388;
	int sizeY = 1040;
	int imageNumber = 0;
	vector<string>  files;
	char * filePath = "C:\\Users\\Lm\\Documents\\MATLAB\\Background estimation\\130507AF9_p0040";
    getFiles(filePath, files); 

	for(int k = 0;k < files.size();k++)
	{
		if( files[k].find("w01.txt")==string::npos)continue;
		cout<<"background"<<files[k]<<endl;
		imageNumber ++;
		if (imageNumber == 21) break;//use 20 images
		unsigned short * image = new unsigned short[sizeX * sizeY];
		FILE *pFile;
		pFile = fopen(files[k].c_str(),"r");
		for(int i=0;i<sizeX*sizeY;i++)
		{
			fscanf(pFile,"%d",image+i);			
		}
		images.push_back(image);
		fclose(pFile);
	}
	unsigned short *Gain = NULL;
	unsigned short *Offset = NULL;
	tp1 = clock();
	calculateGainOffset(images,sizeX,sizeY,&Gain,&Offset);
	tp2 = clock();
	fprintf(stderr,"running time is %f ms\n",(double)(tp2 - tp1) * 1000.0 / CLOCKS_PER_SEC);
		char * outfile1 = "C:\\Users\\Lm\\Documents\\MATLAB\\Background estimation\\gain.txt";
		char * outfile2 = "C:\\Users\\Lm\\Documents\\MATLAB\\Background estimation\\offset.txt";
		FILE *pFile;
		pFile = fopen(outfile1,"w");
		for (int i = 0;i < sizeY;i++)
		{
			for (int j = 0;j<sizeX;j++)
			{
				fprintf(pFile,"%d ",Gain[i*sizeX+j]);
			}
			fprintf(pFile,"\n");
		}
		fclose(pFile);
		pFile = fopen(outfile2,"w");
		for (int i = 0;i < sizeY;i++)
		{
			for (int j = 0;j<sizeX;j++)
			{
				fprintf(pFile,"%d ",Offset[i*sizeX+j]);
			}
			fprintf(pFile,"\n");
		}
		fclose(pFile);
	system("pause");
}

void getFiles( string path, vector<string>& files ) {  
  
    long   hFile   =   0;    
 
    struct _finddata_t fileinfo;    
  
    string p;  
  
    if   ((hFile   =   _findfirst(p.assign(path).append("/*").c_str(),&fileinfo))   !=   -1)  {    
  
        do  {     
            if   ((fileinfo.attrib   &   _A_SUBDIR)) {    
                if   (strcmp(fileinfo.name,".")   !=   0   &&   strcmp(fileinfo.name,"..")   !=   0)    
                    getFiles(   p.assign(path).append("/").append(fileinfo.name), files   );    
            }  else  {    
                files.push_back(   p.assign(path).append("/").append(fileinfo.name)  );  
            }    
        }   while   (_findnext(   hFile,   &fileinfo   )   ==   0);    
  
        _findclose(hFile);    
    }  
}  